﻿using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;

namespace Candy.Infrastructure
{
    public static class ValidationHelper
    {
        public static void ForceValidation(UIElement element)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(element); i++)
            {
                UIElement child = (UIElement)VisualTreeHelper.GetChild(element, i);
                ForceValidation(child);
            }

            BindingExpression bindingExpression = null;

            string uiElementType = element.GetType().ToString();
            switch (uiElementType)
            {
                case "System.Windows.Controls.TextBox":
                    bindingExpression = ((TextBox)element).GetBindingExpression(TextBox.TextProperty);
                    break;

                case "System.Windows.Controls.PasswordBox":
                    bindingExpression = ((PasswordBox)element).GetBindingExpression(PasswordBox.PasswordProperty);
                    break;
            }

            if (bindingExpression == null || bindingExpression.ParentBinding == null) return;
            // if (!bindingExpression.ParentBinding.ValidatesOnExceptions) return;

            bindingExpression.UpdateSource();
        }
    }
}
